package zyy.wcx.datastructures.sparsearray;

/**
 * @program: data-structures-algorithms
 * @description: 稀疏数组
 * @author: WuChengXing
 * @create: 2020-07-06 21:15
 **/
public class SparseArray {
    public static void main(String[] args) {
        int[][] chessArr01 = new int[11][11];
        chessArr01[1][2] = 1;
        chessArr01[2][3] = 2;
        chessArr01[3][4] = 2;
        System.out.println("========== 正常数组 =========");
        for (int[] row : chessArr01) {
            for (int colData : row) {
                System.out.printf("%d\t", colData);
            }
            System.out.println();
        }

        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr01[i][j] != 0) {
                    sum++;
                }
            }
        }

        /**
         * 正常数组转换成稀疏数组
         */
        // 初始化稀疏数组
        int[][] sparseArr = new int[sum + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;

        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr01[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr01[i][j];
                }
            }
        }
        System.out.println();
        System.out.println("========== 正常数组 ==>> 稀疏数组 =========");
        for (int[] row : sparseArr) {
            for (int colData : row) {
                System.out.printf("%d\t", colData);
            }
            System.out.println();
        }

        /**
         * 稀疏数组转换成正常数组
         */
        int[][] chessArr02 = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            chessArr02[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }

        System.out.println();
        System.out.println("========== 稀疏数组 ==>> 正常数组=========");
        for (int[] row : chessArr02) {
            for (int colData : row) {
                System.out.printf("%d\t", colData);
            }
            System.out.println();
        }

    }
}
